package com.hopes.bizz.risk.integral.listener.impl;

import cn.hutool.core.collection.CollUtil;
import com.hopes.bizz.risk.common.constant.IntegralEventEnum;
import com.hopes.bizz.risk.control.entity.RiskMeasureTaskRecordEntity;
import com.hopes.bizz.risk.control.service.RiskMeasureTaskRecordService;
import com.hopes.bizz.risk.integral.bo.IntegralComputeBO;
import com.hopes.bizz.risk.integral.bo.IntegralEvent;
import com.hopes.bizz.risk.integral.entity.RiskIntegralRecordEntity;
import com.hopes.bizz.risk.integral.listener.IntegralEventSupport;
import com.hopes.bizz.risk.integral.service.RiskIntegralEventService;
import com.hopes.bizz.risk.integral.service.RiskIntegralRecordService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * @author yumr
 * @ProjectName bizz
 * @Description 双体系排查任务积分统计
 * @time 2023/8/18 10:06
 */
@Slf4j
@Component("risk_control_integral")
public class RiskIntegralEventHandler extends IntegralEventSupport {

    private final RiskMeasureTaskRecordService riskMeasureTaskRecordService;

    protected RiskIntegralEventHandler(RiskIntegralEventService riskIntegralEventService,
                                       RiskIntegralRecordService riskIntegralRecordService, RiskMeasureTaskRecordService riskMeasureTaskRecordService) {
        super(riskIntegralEventService, riskIntegralRecordService);
        this.riskMeasureTaskRecordService = riskMeasureTaskRecordService;
    }

    @Override
    public void handler(IntegralEvent integralEvent) {
        // 1、业务Id
        final Long businessId = Optional.of(integralEvent).map(IntegralEvent::getBusinessId).orElse(null);
        final RiskMeasureTaskRecordEntity riskMeasureTaskRecord = riskMeasureTaskRecordService.getById(businessId);
        if (Objects.isNull(riskMeasureTaskRecord)) {
            log.error("双体系排查任务数据不存在，业务标识：{}", businessId);
            return;
        }
        // 2、双体系排查任务积分事件
        final IntegralComputeBO integralComputeBO = new IntegralComputeBO(IntegralEventEnum.risk_control_integral, riskMeasureTaskRecord, integralEventMap());
        final List<RiskIntegralRecordEntity> riskIntegralRecordList = integralComputeBO.computeIntegral();
        if (CollUtil.isEmpty(riskIntegralRecordList)) {
            return;
        }
        final boolean b = saveIntegralRecordBatch(riskIntegralRecordList);
        log.debug("双体系排查任务积分事件处理结果：{}", b);
    }
}
